package main

import (
	"container/list"
	"fmt"
	"io"
)

type point struct {
	x, y int
}

// BFS广度优先遍历解决问题
func walk(maze [][]int32, n, m, t int) (bool, int) {
	// 1. 找到起始点 S， 并加入队列
	var S point
	for i := 0; i < n; i++ {
		for j, c := range maze[i] {
			if c == 'S' {
				S.x = i
				S.y = j
			}
		}
	}
	d := list.New()
	d.PushBack(S)
	// 2. 定义移动的行为
	dir := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}
	// 3. 定义去重数组
	used := make([][]bool, n)
	for i := 0; i < n; i++ {
		used[i] = make([]bool, m)
	}
	used[S.x][S.y] = true
	// 4. 开始循环
	cnt := 0
	for d.Len() > 0 {
		l := d.Len()
		for i := 0; i < l; i++ {
			node := d.Remove(d.Front()).(point)
			if node.x == 0 || node.x == n-1 ||
				node.y == 0 || node.y == m-1 {
				return true, cnt
			}
			for _, ac := range dir {
				x := node.x + ac[0]
				y := node.y + ac[1]
				// 如果为 0任何方向都可以通过
				// 否则就要遵循 U D L R的规则
				if (maze[x][y] == '0' ||
					x-node.x == 1 && maze[x][y] == 'U' ||
					x-node.x == -1 && maze[x][y] == 'D' ||
					y-node.y == 1 && maze[x][y] == 'L' ||
					y-node.y == -1 && maze[x][y] == 'R') &&
					!used[x][y] {
					used[x][y] = true
					d.PushBack(point{x, y})
				}
			}
		}
		cnt += 1
		// 如果步数超过 t，也是返回错误
		if cnt > t {
			return false, -1
		}
	}
	return false, -1
}

func main() {
	for {
		// 1. 输入数据
		var t, n, m int
		_, err := fmt.Scanf("%d %d %d", &t, &n, &m)
		if err == io.EOF {
			break
		}
		// 2. 获取迷宫
		maze := make([][]int32, n) // 创建二维数组，实际上是一维数组， 元素又是一维数组
		var s string
		for i := range maze {
			maze[i] = make([]int32, m)
			fmt.Scanf("%s", &s)
			for j, c := range s { // 读取索引
				maze[i][j] = c
			}
		}
		// 3. 查找最短出口
		if ok, num := walk(maze, n, m, t); ok {
			fmt.Println(num)
		} else {
			fmt.Println("NOT POSSIBLE")
		}
	}
}

//arr := [][]int32 {{'1','1','1','1'}, {'1','S','0','1'},{'1','0','1','1'},{'0','U', '1','1'}}
//// 3. 查找最短出口
//if ok, num := walk(arr, 4, 4, 2); ok {
//fmt.Println(num)
//} else {
//fmt.Println("NOT POSSIBLE")
//}
